import request from "umi-request";

//文件导出
const fileExport = async (url, data, title, method = "POST", isParams) => {
    return new Promise((resolve, reject) => {
        request(url, {
            method,
            responseType: "blob",
            data,
            params: isParams ? data : undefined,
            getResponse: true
        })
            .then((res) => {
                let disposition = res.response.headers.get("content-disposition")
                let fileName = ''
                if (disposition) {
                    const match = disposition.match(/filename[*]?=([^;]+)/);
                    if (match && match[1]) {
                        fileName = decodeURIComponent(match[1].replace(/UTF-8''/i, '').replace(/"/g, ''));
                    }
                }
                resolve({ code: 200 });
                const blob = new Blob([res.data]);
                let url = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.href = url; // 给a标签赋上下载地址
                a.download = `${fileName || title || '下载文件.xls'}`;
                a.style.display = "none"; // 让a标签不显示
                a.click(); // a标签自点击
                URL.revokeObjectURL(a.href);
            })
            .catch((err) => {
                resolve({ code: 202 });
            });
    });
};

export default fileExport;
